<template>
  <div class="dashboard-page">
    <h2>控制台概览</h2>
    <p class="sub-title">欢迎回来，邻里管理员！这里是社区的最新概况。</p>

    <div class="stat-cards">
      <StatCard
          icon="fas fa-users"
          title="邻里用户总数"
          :value="allCount.userCount"
          color="#4caf50"
      />
      <StatCard
          icon="fas fa-file-alt"
          title="待审核帖子数"
          :value="allCount.postsCount"
          color="#2196f3"
      />
      <StatCard
          icon="fas fa-heart"
          title="物品数量"
          :value="allCount.itemCount"
          color="#f44336"
      />
      <StatCard
          icon="fas fa-hands-helping"
          title="今日订单数"
          :value="allCount.orderCount"
          color="#ff9800"
      />
    </div>

    <div class="recent-posts">
      <h3>社区热门贴</h3>
      <div v-if="loading" class="loading-container">
        <i class="fas fa-spinner fa-spin"></i>
        <span>加载中...</span>
      </div>
      <template v-else>
        <table>
          <thead>
          <tr>
            <th>帖子ID</th>
            <th>发布人</th>
            <th>标题</th>
            <th>内容</th>
            <th>发布时间</th>
            <th>操作</th>
          </tr>
          </thead>
          <tbody>
          <tr v-for="post in paginatedPosts" :key="post.postId">
            <td>{{ post.postId }}</td>
            <td>{{ post.user.nickname }}</td>
            <td>{{ post.title }}</td>
            <td>{{ post.content }}</td>
            <td>{{ post.createdAt }}</td>
            <td width="200px">
              <button class="action-btn view-btn" @click="look(post)">查看</button>
              <button class="action-btn delete-btn" @click="del(post.postId)">删除</button>
            </td>
          </tr>
          </tbody>
        </table>
        <Pagination
            :currentPage="data.currentPage"
            :totalPages="totalPages"
            @page-changed="handlePageChange"
        />
      </template>
    </div>
  </div>

  <el-dialog v-model="data.showLook" :title="`社区动态详情 - ${selectedPost?.title || ''}`" width="60%">
    <div v-if="selectedPost" class="post-detail">
      <div class="post-header">
        <div class="post-meta">
          <span><strong>帖子ID:</strong> {{ selectedPost.postId }}</span>
          <span><strong>发布人:</strong> {{ selectedPost.user.nickname }}</span>
          <span><strong>发布时间:</strong> {{ selectedPost.createdAt }}</span>
          <span><strong>更新时间:</strong> {{ selectedPost.updatedAt }}</span>
        </div>
      </div>

      <div class="post-content-section">
        <h4>内容详情</h4>
        <div class="content-box">
          {{ selectedPost.content }}
        </div>
      </div>

      <div v-if="selectedPost.images && selectedPost.images.length" class="post-images">
        <h4>图片展示 ({{ selectedPost.images.length }})</h4>
        <div class="image-grid">
          <div v-for="(image, index) in selectedPost.images" :key="index" class="image-item">
            <img :src="image" alt="动态图片" class="post-image" />
          </div>
        </div>
      </div>

      <div class="post-stats">
        <h4>互动数据</h4>
        <div class="stats-grid">
          <div class="stat-item">
            <i class="fas fa-eye"></i>
            <span>浏览: {{ selectedPost.viewCount || 0 }}</span>
          </div>
          <div class="stat-item">
            <i class="fas fa-comment"></i>
            <span>回复: {{ selectedPost.replyCount || 0 }}</span>
          </div>
          <div class="stat-item">
            <i class="fas fa-heart"></i>
            <span>点赞: {{ selectedPost.likeCount || 0 }}</span>
          </div>
          <div class="stat-item">
            <i class="fas fa-star"></i>
            <span>收藏: {{ selectedPost.collectCount || 0 }}</span>
          </div>
        </div>
      </div>
    </div>
  </el-dialog>
</template>

<script setup>
import { ref, computed, onMounted, reactive, watch } from 'vue';
import { useRoute } from 'vue-router';
import StatCard from '@/components/StatCard.vue';
import Pagination from '@/components/Pagination.vue';
import axios from "@/utils/axios.ts";
import { ElMessage } from "element-plus";

const route = useRoute();

// 使用reactive替代ref保持响应式
const allCount = reactive({
  userCount: 0,
  postsCount: 0,
  orderCount: 0,
  itemCount: 0
});

const allHots = ref([]);
const selectedPost = ref(null);
const loading = ref(false);

const data = reactive({
  currentPage: 1,
  postsPerPage: 5,
  showLook: false,
});

// 监听路由变化
watch(() => route.path, (newPath, oldPath) => {
  // 只有当路由切换到当前页面时才重新加载数据
  if (newPath === '/dashboard' && newPath !== oldPath) {
    init();
  }
});

// 初始化加载数据
const init = async () => {
  loading.value = true;

  try {
    // 重置分页到第一页
    data.currentPage = 1;

    // 清空现有数据
    allHots.value = [];

    // 并行加载所有数据
    const [countRes, postsRes] = await Promise.all([
      axios.get("/api/admins/getAllCount"),
      axios.get("/api/admins/getHotPosts")
    ]);

    // 处理统计数据
    if (countRes.code === 200) {
      Object.assign(allCount, countRes.data);
    } else {
      ElMessage.error("统计数据加载失败");
    }

    // 处理帖子数据
    if (postsRes.code === 200) {
      const processedData = postsRes.data.map(post => ({
        ...post,
        images: safeJsonParse(post.images, [])
      }));
      allHots.value = processedData;
      console.log(allHots.value)
    } else {
      ElMessage.error("帖子数据加载失败");
    }
  } catch (error) {
    console.error('加载数据失败:', error);
    ElMessage.error("数据加载失败，请重试");
  } finally {
    loading.value = false;
  }
};

onMounted(() => {
  init();
});

// 安全的JSON解析函数
const safeJsonParse = (str, defaultValue = []) => {
  if (str === undefined || str === null) {
    return defaultValue;
  }

  if (typeof str !== 'string') {
    return str;
  }

  const trimmedString = str.trim();
  if (trimmedString === '') {
    return defaultValue;
  }

  try {
    return JSON.parse(trimmedString);
  } catch (error) {
    console.error('JSON解析失败:', error);
    return defaultValue;
  }
};

// 计算总页数
const totalPages = computed(() => {
  return Math.ceil(allHots.value.length / data.postsPerPage);
});

// 分页数据
const paginatedPosts = computed(() => {
  const start = (data.currentPage - 1) * data.postsPerPage;
  const end = start + data.postsPerPage;
  return allHots.value.slice(start, end);
});

// 处理页码变化
const handlePageChange = (page) => {
  data.currentPage = page;
};

// 查看帖子详情
const look = (post) => {
  selectedPost.value = post;
  data.showLook = true;
};

// 删除帖子
const del = async (postId) => {
  try {
    const res = await axios.post(`/api/admins/delPostById/${postId}`);

    if (res.code === 200) {
      ElMessage.success(res.mes || "删除成功");

      // 直接从数组中移除已删除的帖子
      const index = allHots.value.findIndex(post => post.postId === postId);
      if (index !== -1) {
        allHots.value.splice(index, 1);
      }
      init();
    } else {
      ElMessage.error(res.mes || "删除失败");
    }
  } catch (error) {
    console.error('删除帖子失败:', error);
    ElMessage.error("删除失败，请重试");
  }
};
</script>

<style scoped>
.dashboard-page {
  padding: 30px;
}

.sub-title {
  color: #777;
  font-size: 16px;
  margin-top: -10px;
  margin-bottom: 20px;
}

.stat-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 20px;
  margin-bottom: 30px;
}

.recent-posts {
  background: white;
  padding: 30px;
  border-radius: 12px;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.06);
}

.recent-posts h3 {
  font-size: 20px;
  font-weight: 600;
  margin-bottom: 20px;
  color: #2c3e50;
}

.loading-container {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 40px;
  color: #666;
}

.loading-container i {
  margin-right: 10px;
  font-size: 18px;
}

table {
  width: 100%;
  border-collapse: collapse;
  text-align: left;
}

thead tr {
  background-color: #f5f7fa;
  color: #555;
}

th, td {
  padding: 15px;
  border-bottom: 1px solid #e9ecef;
}

tr:hover {
  background-color: #fafbfd;
}

.action-btn {
  padding: 6px 12px;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  margin-right: 8px;
  font-size: 13px;
}

.view-btn {
  background-color: #3498db;
  color: white;
}

.view-btn:hover {
  background-color: #2980b9;
}

.delete-btn {
  background-color: #e74c3c;
  color: white;
}

.delete-btn:hover {
  background-color: #c0392b;
}

/* 帖子详情样式 */
.post-detail {
  padding: 10px;
}

.post-header {
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #eee;
}

.post-meta {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 10px;
}

.post-meta span {
  font-size: 14px;
  color: #666;
}

.post-content-section {
  margin-bottom: 20px;
}

.post-content-section h4 {
  margin-bottom: 10px;
  color: #333;
}

.content-box {
  padding: 15px;
  background: #f9f9f9;
  border-radius: 6px;
  border-left: 4px solid #3498db;
  line-height: 1.6;
}

.post-images {
  margin-bottom: 20px;
}

.post-images h4 {
  margin-bottom: 10px;
  color: #333;
}

.image-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 10px;
}

.post-image {
  width: 100%;
  height: 100px;
  object-fit: cover;
  border-radius: 6px;
  cursor: pointer;
  transition: transform 0.3s;
}

.post-image:hover {
  transform: scale(1.05);
}

.post-stats h4 {
  margin-bottom: 10px;
  color: #333;
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 15px;
}

.stat-item {
  display: flex;
  align-items: center;
  padding: 10px;
  background: #f5f7fa;
  border-radius: 6px;
}

.stat-item i {
  margin-right: 8px;
  color: #3498db;
  width: 20px;
}
</style>